<?php

class media_lib {
 	
	private $ci;
	
 	public function __construct()
 	{
 		log_message('debug', 'Media library initialized.');
		
		$this->ci =& get_instance();
 	}
	
	
	public function handle_upload($sFile)
	{
	
		$aMediaTitle = explode('.', $sFile);
		$sMediaExt = array_pop($aMediaTitle);// knock off the file extension
		$aMediaTitle = join('.', $aMediaTitle);
		$aMediaTitle = explode('/', $aMediaTitle);
		$sMediaTitle = array_pop($aMediaTitle);
		log_message('debug', 'sMediaExt: '.$sMediaExt);
		log_message('debug', 'sMediaTitle: '.$sMediaTitle);
		
		
		$this->add_file_to_media($sFile, strtolower($sMediaExt), $sMediaTitle);
	}	


	public function add_file_to_media($sFile, $sMediaExt, $sMediaTitle, $iFolder = null, $bResizeWeb = true) 
	{		
		$this->ci->load->model('db/media_extensions', 'media_extensions');
		
		$this->ci->media_extensions->extension_ext = $sMediaExt;
		
		$qMediaExt = $this->ci->media_extensions->get(array(), 1);
		
		if ($qMediaExt->num_rows() === 0)
		{
			log_message('debug', 'bugging out! No file extensions');
			return false;	
		}
		
		
		$iUserId = $this->ci->input->post('iUserId', true, 1);
		
		if ($iUserId === false)
		{
			$iUserId = $this->ci->user->userId;	
		}
		
		
		$oMediaExt = $qMediaExt->row(0);
		
		
		$this->ci->load->model('db/media', 'media');
		
		$this->ci->media->media_subfolder = true;
		
		// get the max sub folder currently used in media table
		$iSubFolder = $this->ci->media->get_max();
		
		log_message('debug', $this->ci->db->last_query());
		
		if ($iSubFolder === null)
		{
			$iSubFolder = 0;	
		}
		
		$this->ci->media->clear();
		
		$this->ci->media->media_subfolder = $iSubFolder;
		
		$iSubFolderCount = $this->ci->media->get_count();
		
		$this->ci->media->clear();

		if ($iSubFolderCount > $this->ci->config->item('admin_media_folder_max_count'))
		{
			$iSubFolder++;	
		}
		
		$this->ci->load->library('image_lib');
		
		// move the file into the originals folders
		
		$aMediaFileDims = $this->ci->config->item('admin_media_file_dims');
		
		// firstly, insert the media record
		$this->ci->media->folder_id = $iFolder;
		$this->ci->media->media_subfolder = $iSubFolder;
		$this->ci->media->user_id = $iUserId;
		$this->ci->media->media_epoch = time();
		$this->ci->media->media_title = $sMediaTitle;
		$this->ci->media->extension_id = $oMediaExt->extension_id;
		$this->ci->media->media_desc = '';
		$this->ci->media->media_size = 0;
		
		$iMediaId = $this->ci->media->save();
		
		$this->ci->media->clear();
		
		
		if ($oMediaExt->extension_thumb !== 'N')
		{
			// if our media has a thumbnail, then we have dimensions
			$this->ci->load->model('db/media_dimensions', 'media_dimensions');	
		}
		
		foreach ($aMediaFileDims as $sMediaType => $aMediaProps)
		{
			list($sMediaTypeText, $iMediaMaxWidth, $iMediaMaxHeight) = $aMediaProps;
			
			if ($oMediaExt->extension_thumb === 'N')
			{
				if ($sMediaType === 'W')
				{
					log_message('quvex', 'We do not have a thumbnail: '.$oMediaExt->extension_thumb);
					// we don't have a thumb. What to do?	
					
					$sFolderDest = $this->ci->config->item('admin_media_dir_url').$sMediaTypeText.'/'.$iSubFolder.'/';
					$sFolderPath = $this->ci->config->item('admin_media_dir').$sMediaTypeText.'/'.$iSubFolder.'/';
					
					log_message('quvex', 'sFolderDest: '.$sFolderDest);
					if (file_exists($sFolderPath) === false)
					{
						log_message('quvex', 'Making directory: '.$sFolderPath);
						mkdir($sFolderPath, 0777); 
						log_message('quvex', 'Directory made');
					}
					
					log_message('quvex', 'Failing here?');
					$sImageDest = $sFolderDest.$iMediaId.'.'.$sMediaExt;
					$sImagePath = $sFolderPath.$iMediaId.'.'.$sMediaExt;
					
					log_message('quvex', 'Copying '.$sFile.' to '.$sImagePath);
	
					copy($sFile, $sImagePath);				
				}
				
			}
			else 
			{
				$sFolderDest = $this->ci->config->item('admin_media_dir_url').$sMediaTypeText.'/'.$iSubFolder.'/';
				$sFolderPath = $this->ci->config->item('admin_media_dir').$sMediaTypeText.'/'.$iSubFolder.'/';
				
				log_message('debug', 'sFolderDest: '.$sFolderDest);
				if (file_exists($sFolderPath) === false)
				{
					log_message('debug', 'Making directory: '.$sFolderPath);
					mkdir($sFolderPath, 0777); 
					log_message('debug', 'Directory made');
				}
				
				log_message('debug', 'Failing here?');
				$sImageDest = $sFolderDest.$iMediaId.'.'.$sMediaExt;
				$sImagePath = $sFolderPath.$iMediaId.'.'.$sMediaExt;
				
				log_message('debug', 'Copying '.$sFile.' to '.$sImagePath);

				copy($sFile, $sImagePath);
				
				$aImageSize = getimagesize($sImagePath);
				
				if (($iMediaMaxWidth > 0) && ($iMediaMaxHeight > 0))
				{
					// if we're larger than allowed
					if (($aImageSize[0] > $iMediaMaxWidth) || ($aImageSize[1] > $iMediaMaxHeight))
					{
						if ((($sMediaType === 'W') && ($bResizeWeb === true)) || ($sMediaType !== 'W'))
						{
				
							$config['image_library'] = 'gd2';
							$config['source_image'] = $sImagePath;
							$config['create_thumb'] = false;
							$config['maintain_ratio'] = true;
							$config['width'] = $iMediaMaxWidth;
							$config['height'] = $iMediaMaxHeight;
							$config['master_dim'] = 'auto';
		
							$this->ci->image_lib->initialize($config);
					
							$this->ci->image_lib->resize();
							$this->ci->image_lib->clear();
						}
					}
				}
				
				
				$aImageSize = getimagesize($sImagePath);
				
				
				$this->ci->media_dimensions->media_id = $iMediaId;
				$this->ci->media_dimensions->dimension_type = $sMediaType;
				$this->ci->media_dimensions->dimension_width = $aImageSize[0];
				$this->ci->media_dimensions->dimension_height = $aImageSize[1];
				
				$this->ci->media_dimensions->save();
				$this->ci->media_dimensions->clear();
			}
			
			
			if ($sMediaType === 'W')
			{
				$this->ci->media->media_id = $iMediaId;
				$this->ci->media->media_size = filesize($sImagePath);
				$this->ci->media->save();
				$this->ci->media->clear();
			}
			
		}
		
		
		//unlink($sFile);
		
		
		return $iMediaId;
		
	}
	
	
	public function get_folder_hierarchy($aOptions = array(), $aPersistentOptions = array())
	{
		$this->ci->media_folders->clear();
		
		$aOptions = array_merge($aOptions, $aPersistentOptions);
		
		$qFolders = $this->ci->media_folders->get(array('where' => $aOptions));
		
		if($qFolders->num_rows() > 0)
		{
			for($i = 0; $i < $qFolders->num_rows(); $i++)
			{
				$qFolders->row($i)->qChildFolders = $this->get_folder_hierarchy(array('folder_parent_id' => $qFolders->row($i)->folder_id), $aPersistentOptions);
			}
		}
		
		return $qFolders;
	}
	
	public function build_folder_hierarchy($qFolders, $sContainerElement = 'ul', $sContainerElementClass = 'page_container', $sListElement = 'li', $sListElementClass = 'folder', $bIncAnchor = false, $sAnchorHref = '', $sAnchorField = NULL)
	{
		$sFolders = '';
		
		if($qFolders->num_rows() > 0)
		{
			$sFolders .= '<'.$sContainerElement.' class="'.$sContainerElementClass.'">';
			
			for($i = 0; $i < $qFolders->num_rows(); $i++)
			{
				$sFolders .= '<'.$sListElement.' class="'.$sListElementClass.'" id="'.$sListElementClass.'_'.$qFolders->row($i)->folder_id.'">';
				
				if($bIncAnchor)
				{
					$sHref = $sAnchorHref != '' ? $sAnchorHref : '#';
					$sHref .= ($sAnchorField != false && isset($qFolders->row($i)->{$sAnchorField})) ? $qFolders->row($i)->{$sAnchorField} : '';
					$sFolders .= '<a href="'.$sHref.'"';
					$sFolders .= $sHref === '#' ? ' onclick="return false;"' : '';
					$sFolders .= '>';
				}
				
				$sFolders .= $qFolders->row($i)->folder_title;
				
				if($bIncAnchor)
				{
					$sFolders .= '</a>';
				}
				
				if(isset($qFolders->row($i)->qChildFolders) && $qFolders->row($i)->qChildFolders->num_rows() > 0)
				{
					$sFolders .= $this->build_folder_hierarchy($qFolders->row($i)->qChildFolders, $sContainerElement, $sContainerElementClass, $sListElement, $sListElementClass, $bIncAnchor, $sAnchorHref, $sAnchorField);
				}
				
				$sFolders .= '</'.$sListElement.'>';
			}
			
			$sFolders .= '</'.$sContainerElement.'>';
		}
		
		return $sFolders;
	}

}

?>